package cn.itcast.bos.service.system.impl;

import cn.itcast.bos.dao.system.RoleRepository;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.MenuService;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private MenuService menuService;

    @Override
    public List<Role> findByUser(User user) {
        if ("admin".equals(user.getUsername())) {
            return roleRepository.findAll();
        } else {
            return roleRepository.findByUser(user.getId());
        }
    }

    @Override
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

    @Override
    public void save(Role model, String[] permissionIds, String menuIds) {
        if (StringUtils.isNoneBlank(permissionIds)) {
            for (String permissionId : permissionIds) {
                Permission permission = permissionService.findById(Integer.parseInt(permissionId));
                model.getPermissions().add(permission);
            }
        }
        String[] menuIdArray = menuIds.split(",");
        if (StringUtils.isNoneBlank(menuIdArray)) {
            for (String menuId : menuIdArray) {
                Menu menu = menuService.findById(Integer.parseInt(menuId));
                model.getMenus().add(menu);
            }
        }
        roleRepository.save(model);
    }

    @Override
    public Role findById(int roleId) {
        return roleRepository.findOne(roleId);
    }
}
